<?php
// +----------------------------------------------------------------------
// | Media媒体服务服务层
// +----------------------------------------------------------------------
// | 主要服务于Media媒体数据处理
// +----------------------------------------------------------------------
// | 错误编码头 210xxx
// +----------------------------------------------------------------------
namespace common\service;

use common\model\CosMediaModel;
use support\SingletonTrait;

class CosMediaService
{

    // 单例工具
    use SingletonTrait;

    /**
     * 查询添加
     * @param $data
     * @return array|bool|mixed|string
     * @throws \Exception
     */
    public function findAddMedia($data)
    {
        $cosMedia = model(CosMediaModel::class)->where(['request_url' => $data["request_url"], "cos_key" => $data["cos_key"]])->find();
        if (!empty($cosMedia)) {
            $cosMedia['param'] = json_decode($cosMedia['param'], true);
            //如果存在额外参数 ,需要更新param且去除掉为空的值且融合覆盖
            if (!empty($data['param'])) {
                $param = $data['param'];
                $param = array_filter($param, function ($paramItem) {
                    return !empty($paramItem);
                });
                $cosMediaParam = $cosMedia['param'];
                if (!empty($cosMediaParam)) {
                    $cosMediaParam = array_merge($cosMediaParam, $param);
                } else {
                    $cosMediaParam = $param;
                }
                $updateData = [
                    'id' => $cosMedia['id'],
                    'param' => $cosMediaParam
                ];
                $cosMediaData = model(CosMediaModel::class)->modifyItem($updateData);
                if (!empty($cosMediaData)) {
                    $cosMedia = $cosMediaData;
                }
            }
            return $cosMedia;
        }
        return model(CosMediaModel::class)->addItem($data);
    }
}
